home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: in2.uu.net!allegra!alice!ark
- From: ark@research.att.com (Andrew Koenig)
- Subject: Re: Can copy constructor and operator= share code?
- Message-ID: <DnvICD.5DJ@research.att.com>
- Organization: AT&T Research, Murray Hill NJ
- References: <4h2kcn$40d@rap.SanDiegoCA.ATTGIS.COM> <199603040709.a35476@iz.maus.de> <4hk3bh$1j4s@flute.aix.calpoly.edu>
- Date: Thu, 7 Mar 1996 01:19:25 GMT
-
- In article <4hk3bh$1j4s@flute.aix.calpoly.edu> mporcell@flute.aix.calpoly.edu (Michael Anthony Porcelli) writes:
-
- > Here's a style tip from a senior level C++/OO class on exactly this topic.
- > In fact our teacher *required* this for all of our classes and frankly I
- > believe this is a GREAT C++ tip for good OO/SoftEng.
-
- Well, almost. See below.
-
- > X(X& x)
- > { Duplicate(x); } //one-statement, in-line copy constructor.
-
- > operator= (X& x)
- > { Delete(); Duplicate(x); } //two-statement, in-line op=
-
- Oops! This fails when you try to assign an object to itself,
- because it destroys the objects value and then assigns the destroyed
- value to itself. It also implicitly returns an undefined integer
- value, instead of returning a reference to the left-hand side
- the way the built-in assignment operator does. Finally, the
- operand should be const.
-
- My revised version:
-
- X& operator=(const X& x)
- { if (this != &x) { Delete(); Duplicate(x); } return *this; }
-
- > ~X()
- > { Delete(); } //one-statement, in-line destructor.
-
- > Pretty nifty, eh? I believe that all class design should be done this way.
-
- It's a good strategy if you fix the bugs described above.
- --
- --Andrew Koenig
- ark@research.att.com
-